package com.javaking.clanteam.studentutils.sql;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

import com.javaking.clanteam.studentutils.courses.assingments.AssignmentData;

public class AssignmentHelper extends SQLiteOpenHelper implements BaseColumns {
	
	public static final String DATABASE_NAME = CourseHelper.DATABASE_NAME;
	public static final int DATABASE_VERSION = CourseHelper.DATABASE_VERSION;
	
	public static final String ASSINGMENT_TABLE_NAME = "assingments";
	public static final String COLUMN_ID = _ID;
	public static final String COLUMN_CREATED = "created";
	public static final String COLUMN_NAME = "name";
	public static final String COLUMN_ASSIGNED = "assigned";
	public static final String COLUMN_DUE = "due";
	public static final String COLUMN_COURSE_ID = "courseId";
	public static final String COLUMN_PRIORITY = "priority";
	public static final String COLUMN_IS_PROJECT = "project";
	
	public static final String ASSIGNMENT_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
			+ ASSINGMENT_TABLE_NAME + " ( "
			+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
			+ COLUMN_CREATED + " INTEGER DEFAULT ( strftime('%s','now')*1000),"
			+ COLUMN_NAME + " TEXT NOT NULL,"
			+ COLUMN_ASSIGNED + " INTEGER DEFAULT ( strftime('%s','now')*1000),"
			+ COLUMN_DUE + " INTEGER DEFAULT ( (strftime('%s','now')+60*60*24)*1000),"
			+ COLUMN_COURSE_ID + " INTEGER NOT NULL,"
			+ COLUMN_PRIORITY + " INTEGER DEFAULT 0,"
			+ COLUMN_IS_PROJECT + " INTEGER DEFAULT 0"
			+ " );";
	private Context mContext;
	
	
	public AssignmentHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		mContext = context;
		
		getWritableDatabase();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(ASSIGNMENT_TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersivalueon, int newVersion) {
		// TODO Preserve data
		
		purgeTable();
	}

	public void purgeTable() {
		Log.w(getClass().getName(), "DROPPING ASSIGNMENT TABLE!! All data will be lost.");
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("DROP TABLE IF EXISTS "+ASSINGMENT_TABLE_NAME+"; ");
		onCreate(db);
	}
	
	public void addAssingment(AssignmentData assingment) {
		long id = getWritableDatabase().insertOrThrow(ASSINGMENT_TABLE_NAME, null, assingment.toContentValues());
		if (id!=-1) {
			assingment.setId(id);
		}
	}
	
	/**
	 * Retrieve the first 
	 * @param id
	 * @return
	 */
	public AssignmentData getAssignment(long id) {
		Cursor cursor = getReadableDatabase().query(ASSINGMENT_TABLE_NAME,null,COLUMN_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
		return AssignmentData.buildFromCursor(cursor, mContext);
	}

}
